package com.jayson.server;

import com.jayson.server.catalina.*;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;

public class RequestProcessor implements Runnable {

    private Socket socket;

    private List<Host> hostList;

    private HttpServlet httpServlet;

    public RequestProcessor(Socket socket, List<Host> hostList) {
        this.socket = socket;
        this.hostList = hostList;
    }

    @Override
    public void run() {
        try {

            InputStream inputStream = socket.getInputStream();
            Request request = new Request(inputStream);

            OutputStream outputStream = socket.getOutputStream();
            Response response = new Response(outputStream);

            Servlet httpServlet = getServlet(request, this.hostList);
            long s = System.currentTimeMillis();
            if(httpServlet == null){
                response.outputHtml(request.getUrl());
            } else {
                httpServlet.service(request, response);
            }
            System.out.println("====>>>>耗时：" + (System.currentTimeMillis() - s));
            socket.close();
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 根据URL去Mapper对象中查找servlet
     * @param request
     * @param hostList
     * @return
     */
    private Servlet getServlet(Request request, List<Host> hostList) {
        for (Host host : hostList) {
            if(!request.getHost().equals(host.getName())){
                continue;
            }
            List<Context> contexts = host.getContexts();
            for (Context context : contexts) {
                List<Wrapper> wrappers = context.getWrappers();
                for (Wrapper wrapper : wrappers) {
                    if(request.getUrl().equals("/" + context.getContext() + wrapper.getUrlPatten())){
                        return wrapper.getServlet();
                    }
                }

            }

        }
        return null;
    }
}
